package com.cn.xiongmeng.czlxz.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;


import com.cn.xiongmeng.czlxz.MainApplication;
import com.cn.xiongmeng.czlxz.R;
import com.cn.xiongmeng.czlxz.databinding.ActivityMainBinding;
import com.cn.xiongmeng.czlxz.network.HttpClient;
import com.cn.xiongmeng.czlxz.taku.InterstitialAd;
import com.cn.xiongmeng.czlxz.ui.AvatarFragment;
import com.cn.xiongmeng.czlxz.ui.BannerFragment;
import com.cn.xiongmeng.czlxz.ui.LoadingFragment;
import com.cn.xiongmeng.czlxz.ui.TasksFragment;
import com.cn.xiongmeng.czlxz.ui.TlFragment;

import org.json.JSONException;
import org.json.JSONObject;

public class IndexActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "MainApplication:IndexActivity";
    private ActivityMainBinding binding;
    public TextView tvTotalTl;
    private LoadingFragment loadingFragment;
    private AvatarFragment avatarFragment;
    private TlFragment tlFragment;
    private TasksFragment tasksFragment;
    private BannerFragment bannerFragment;
    private HttpClient httpClient;
    private Handler mHandler;
    private FrameLayout bannerViewContainer;
    public int curReward;
    public int curTargetReward;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_index);

        // 1、几个按钮的初始化，监听
        initClickableView();
        // 2、几个fragment的初始化
        initFragments();

        httpClient = new HttpClient(this);
        mHandler = new Handler(Looper.getMainLooper());

        // 3、初始化BannerViewContrainer，默认显示
        initBannerViewContrainer();

        // 4、加载、展示Banner
        // loadBannerAd();

    }
    // 初始化几个可点击的View
    private void initClickableView(){
        ImageView btnAvatar = findViewById(R.id.btn_avatar);
        ImageView btnTl = findViewById(R.id.btn_tl);
        ImageView btnRw = findViewById(R.id.btn_rw);
        ImageView btnWork = findViewById(R.id.btn_work);
        tvTotalTl = findViewById(R.id.tv_total_tl);

        btnAvatar.setOnClickListener(this);
        btnTl.setOnClickListener(this);
        btnRw.setOnClickListener(this);
        btnWork.setOnClickListener(this);
    }
    // 初始化几个Fragment
    private void initFragments(){
        loadingFragment = new LoadingFragment();
        avatarFragment = new AvatarFragment();
        tlFragment = new TlFragment();
        tasksFragment = new TasksFragment();
        bannerFragment = new BannerFragment();
    }
    // 初始化BannerViewContrainer，默认显示
    private void initBannerViewContrainer(){
        // ConstraintLayout constraintLayout = findViewById(R.id.constraint_layout_index);
        // bannerViewContainer = new FrameLayout(this);
        bannerViewContainer = findViewById(R.id.banner_view_container);

        // 设置宽高
        float ratio = 320/60f;
        int width = getResources().getDisplayMetrics().widthPixels;//定一个宽度值，比如屏幕宽度
        int height = (int) (width / ratio);

        ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(
                ConstraintLayout.LayoutParams.MATCH_PARENT,
                height
        );
        // bannerViewContainer.setBackgroundColor(Color.parseColor("#A1FFFFFF"));

        layoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
        layoutParams.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID;
        layoutParams.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
        layoutParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
        layoutParams.horizontalBias = 0.5f;
        layoutParams.verticalBias = 0.98f;

        bannerViewContainer.setLayoutParams(layoutParams);
        // constraintLayout.addView(bannerViewContainer);
    }

    // 加载、展示Banner广告
    private void loadBannerAd(){
        MainApplication app = (MainApplication)getApplication();

        // 1、定义子视图（View）在 FrameLayout 中的布局特性（也就是，定义bannerView在FrameLayout 中的布局特性）
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.gravity = Gravity.CENTER;
        bannerViewContainer.addView(app.getBannerView(), layoutParams);
        app.getBannerView().loadAd();
    }

    /* 在这设置体力、任务的值 */
    @Override
    protected void onStart() {
        super.onStart();

        Log.d(TAG, "onStart");
        // showFragment(bannerFragment, "fragment_banner");
        setTotalTl();
        setTaskCount();
    }

    @Override
    protected void onResume() {
        super.onResume();

        Log.d(TAG, "onResume");

        showFragment(bannerFragment, "fragment_banner");
    }

    @Override
    protected void onPause() {
        super.onPause();

        Log.d(TAG, "onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();

        Log.d(TAG, "onStop");

        // removeFragment(bannerFragment);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        Log.d(TAG, "onDestroy");
    }

    @Override
    public void onClick(View v){
        if (v.getId() == R.id.btn_avatar){
            Log.d(TAG, "点击头像");

            showFragment(avatarFragment, "fragment_avatar");
            // 弹出插屏广告
            // 开启后台线程
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            InterstitialAd.showInterstitialAd(IndexActivity.this);
                        }
                    });
                }}).start();
        } else if (v.getId() == R.id.btn_tl) {
            Log.d(TAG, "点击体力");

            showFragment(tlFragment, "fragment_tl");

        } else if (v.getId() == R.id.btn_rw) {
            Log.d(TAG, "点击任务");

            showFragment(tasksFragment, "fragment_tasks");

        } else if (v.getId() == R.id.btn_work) {
            Log.d(TAG, "点击工作按钮");

            removeOneTl();
        }
    }
    private void setTotalTl(){
        SharedPreferences prefs = this.getSharedPreferences("AppPrefs", Context.MODE_PRIVATE);
        String fakeUser = prefs.getString("fakeUser", "");

        if (fakeUser.length() != 0){
            try {
                JSONObject jsonObject = new JSONObject(fakeUser);
                String totalTl = jsonObject.getString("total_tl");
                tvTotalTl.setText(totalTl);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    // 根据缓存，同步 curReward、curTargetReward
    private void setTaskCount(){
        SharedPreferences prefs = this.getSharedPreferences("AppPrefs", Context.MODE_PRIVATE);
        String fakeUser = prefs.getString("fakeUser", "");

        if (fakeUser.length() != 0){
            try {
                JSONObject jsonObject = new JSONObject(fakeUser);
                curReward = jsonObject.getInt("cur_reward");
                curTargetReward = jsonObject.getInt("cur_target_reward");
                Log.d(TAG, "setTaskCount: curReward: " + curReward);
                Log.d(TAG, "setTaskCount: curTargetReward: " + curTargetReward);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    private void removeOneTl(){
        int _totalTl = Integer.parseInt(tvTotalTl.getText().toString());
        if (_totalTl == 0){
            // 测试没问题
            runOnUiThread(() -> {
                Toast.makeText(this, "体力不足！", Toast.LENGTH_LONG).show();
            });
        } else {
            SharedPreferences prefs = this.getSharedPreferences("AppPrefs", Context.MODE_PRIVATE);
            String fakeUser = prefs.getString("fakeUser", "");

            if (fakeUser.length() != 0){
                try {
                    JSONObject jsonObject = new JSONObject(fakeUser);
                    String fakeUid = jsonObject.getString("fake_uid");

                    JSONObject jsonObject2 = new JSONObject();
                    jsonObject2.put("fakeUid", fakeUid);
                    String jsonString = jsonObject2.toString();

                    String url = "https://little-moon.fun/remove_one_tl/";

                    httpClient.sendPostRequest(url, jsonString, new HttpClient.Callback() {
                        @Override
                        public void onFailure(Exception e) {
                            // 测试没问题
                            runOnUiThread(() -> {
                                Toast.makeText(IndexActivity.this, "请稍后再试！", Toast.LENGTH_LONG).show();
                            });
                        }

                        @Override
                        public void onResponse(String response) {
                            Log.d(TAG, "Post 请求成功: " + response); // Log 成功响应
                            // 1、提示（测试没问题）
                            runOnUiThread(() -> {
                                Toast.makeText(IndexActivity.this, "体力 - 1", Toast.LENGTH_LONG).show();
                            });
                            // 2、修改数值（测试没问题）
                            String _totalTl = tvTotalTl.getText().toString();
                            String totalTl = String.valueOf(Integer.parseInt(_totalTl) - 1);
                            runOnUiThread(() -> {
                                tvTotalTl.setText(totalTl);
                            });
                            // 3、更新缓存（测试没问题）
                            try{
                                jsonObject.put("total_tl", totalTl);
                                SharedPreferences.Editor editor = prefs.edit();

                                editor.putString("fakeUser", jsonObject.toString());
                                editor.apply(); // apply异步，commit同步

                                // 4、跳转（测试没问题）
                                runOnUiThread(() -> {
                                    Intent intent = new Intent(IndexActivity.this, WorkActivity.class);
                                    startActivity(intent);
                                });
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                // 测试没问题
                runOnUiThread(() -> {
                    Toast.makeText(IndexActivity.this, "请稍后再试！", Toast.LENGTH_LONG).show();
                });
            }
        }
    }

    private void showFragment(Fragment fragment, String str) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        if (fragment.isAdded()) {
            fragmentTransaction.show(fragment);
        } else {
            if (str == "fragment_banner"){
                fragmentTransaction.add(R.id.banner_view_container, fragment, str);
            } else {
                fragmentTransaction.add(R.id.fragment_container, fragment, str);

            }
        }
        fragmentTransaction.commit();

    }
    private void removeFragment(Fragment fragment){
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        if (fragment.isAdded()) {
            fragmentTransaction.remove(fragment);
        }
        fragmentTransaction.commit();
    }
}